<?php
/***********************************************************
 * 模板管理
 * @作者 pcfcms <1131680521@qq.com>
 * @版权 广州市春风科技有限公司
 * @主页 http://www.pcfcms.com
 * @时间 2019年12月21日
***********************************************************/
namespace app\admin\controller\channel;
use app\admin\controller\Base;
use app\admin\logic\FilemanagerLogic;
use think\facade\Cache;
use think\facade\Request;
use think\facade\Db;
use think\facade\Session;
class Filemanager extends Base
{
    public $filemanagerLogic;
    public $baseDir = '';
    public $maxDir = '';
    public $globalTpCache = array();
    public $popedom = '';
    public function initialize() {
        parent::initialize();
        $this->filemanagerLogic = new FilemanagerLogic(); 
        $this->globalTpCache = $this->filemanagerLogic->globalTpCache;
        $this->baseDir = $this->filemanagerLogic->baseDir; // 服务器站点根目录绝对路径     
        $this->maxDir = $this->filemanagerLogic->maxDir; // 默认文件管理的最大级别目录
        $ctl_act = Request::controller().'/index';
        $this->popedom = appfile_popedom($ctl_act);
    }

    public function index()
    {
        //验证权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        //获取到所有GET参数
        $param = input('param.', '', null);
        $activepath = input('param.activepath', '', null);
        $activepath = $this->filemanagerLogic->replace_path($activepath, ':', true);
        // 当前目录路径
        $activepath = !empty($activepath) ? $activepath : $this->maxDir;
        $tmp_max_dir = preg_replace("#\/#i", "\/", $this->maxDir);
        if (!preg_match("#^".$tmp_max_dir."#i", $activepath)) {
            $activepath = $this->maxDir;
        }
        $inpath = "";
        $activepath = str_replace("..", "", $activepath);
        $activepath = preg_replace("#^\/{1,}#", "/", $activepath); // 多个斜杆替换为单个斜杆
        if($activepath == "/") $activepath = "";
        if(empty($activepath)) {
            $inpath = $this->baseDir.$this->maxDir;
        } else {
            $inpath = $this->baseDir.$activepath;
        }
        $inpath = str_replace("\/", "/", $inpath); // 多个斜杆替换为单个斜杆
        $list = $this->filemanagerLogic->getDir($inpath, $activepath);
        $assign_data['list'] = $list;
        $assign_data['activepath'] = $activepath;
        $assign_data['edittplpass'] = Session::get('edittplpass') ? true : false;
        $this->assign($assign_data);
        return $this->fetch();
    }
    
    // 密码访问
    public function edittpl()
    {
        Session::set('edittplpass',false);
        if (!Session::get('edittplpass')) {
            if (md5($_POST['pass']) != md5('PCFCMS'.date('mdH'))) {
                Session::set('edittplpass',false);
                $result = ['status' => false, 'msg' => '密码错误！'];
                return $result;
            }else{
                Session::set('edittplpass',true);
            }
            $result = ['status' => true, 'msg' => 'OK'];
            return $result;
        }else{
            $result = ['status' => false, 'msg' => '请联系技术人员QQ：1131680521'];
            return $result;
        }
    }

    public function lists()
    {
        //验证权限
        if(!$this->popedom["list"] || !Session::get('edittplpass')){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        // 获取到所有GET参数
        $param = input('param.', '', null);
        $activepath = input('param.activepath', '', null);
        $activepath = $this->filemanagerLogic->replace_path($activepath, ':', true);
        if (empty($activepath) || $this->maxDir == $activepath) {
            $domain = Request::baseFile().'/channel.filemanager/index';
            $this->errorNotice('不存在目录！',$domain);
        }
        // 当前目录路径
        $activepath = !empty($activepath) ? $activepath : $this->maxDir;
        $tmp_max_dir = preg_replace("#\/#i", "\/", $this->maxDir);
        if (!preg_match("#^".$tmp_max_dir."#i", $activepath)) {
            $activepath = $this->maxDir;
        }
        $inpath = "";
        $activepath = str_replace("..", "", $activepath);
        $activepath = preg_replace("#^\/{1,}#", "/", $activepath); //多个斜杆替换为单个斜杆
        if($activepath == "/") $activepath = "";
        if(empty($activepath)) {
            $inpath = $this->baseDir.$this->maxDir;
        } else {
            $inpath = $this->baseDir.$activepath;
        }
        $list = $this->filemanagerLogic->getDirFile($inpath, $activepath);
        // 文件操作
        $assign_data['list'] = $list;
        $assign_data['replaceImgOpArr'] = $this->filemanagerLogic->replaceImgOpArr;
        $assign_data['editOpArr'] = $this->filemanagerLogic->editOpArr;
        $assign_data['renameOpArr'] = $this->filemanagerLogic->renameOpArr;
        $assign_data['delOpArr'] = $this->filemanagerLogic->delOpArr;
        $assign_data['moveOpArr'] = $this->filemanagerLogic->moveOpArr;
        $assign_data['activepath'] = $activepath;
        $assign_data['maxDir'] = $this->maxDir;
        $this->assign($assign_data);
        return $this->fetch();
    }
    // 替换图片
    public function replace_img()
    {
        $gzpcfglobal = get_global();
        $result = ['status' => false,'msg' => '失败','url' => ''];
        if (Request::isPost()) {
            //验证权限
            if(!$this->popedom["modify"] || !Session::get('edittplpass')){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                    return $result;                    
                }
            }
            $activepath = input('post.activepath/s', '');
            $filename = input('post.filename/s', '');
            $upfile = input('post.upfile/s', '');
            if (empty($activepath) || empty($filename)) {
                $result['status'] = false;
                $result['msg']  = '参数有误';
                return $result;
            }
            if (empty($upfile)) {
                $result['status'] = false;
                $result['msg'] = '请上传图片！';
                return $result;
            }else {
                $image_type = tpCache('basic.image_type');
                $fileExt = !empty($image_type) ? str_replace('|', ',', $image_type) : config('params.image_ext');
                $image_types = explode(',', $fileExt);
                $image_ext = pathinfo($filename, PATHINFO_EXTENSION);
                if (!in_array($image_ext, $image_types)) {
                    $result['status'] = false;
                    $result['msg']    = '上传图片后缀名必须为'.$fileExt;
                    return $result;
                }
            }
            $source = preg_replace('#^/uploads/#i', 'uploads/', $upfile);
            $destination = trim($activepath, '/').'/'.$filename;
            if (@copy($source, $destination)) {
                @unlink($source);
                $result['status'] = true;
                $result['msg']    = '操作成功！';
                $result['url'] = url('/channel.Filemanager/lists', array('activepath'=>$this->filemanagerLogic->replace_path($activepath, ':', false)))->suffix(false)->domain(true)->build();
                return $result;
            } else {
                $result['status'] = false;
                $result['msg']  = '操作失败！';
                return $result;
            }
        }
        $filename = input('param.filename/s', '', null);
        $activepath = input('param.activepath/s', '', null);
        $activepath = $this->filemanagerLogic->replace_path($activepath, ':', true);
        if ($activepath == "") {
            $activepathname = "根目录";
        }else {
            $activepathname = $activepath;
        }
        $info = array(
            'activepath'    => $activepath,
            'activepathname'    => $activepathname,
            'filename'  => $filename,
        );
        $this->assign('info', $info);
        return $this->fetch();
    }
    //编辑
    public function edit()
    {
        $result = ['status' => false,'msg' => '失败','url' => ''];
        if (Request::isPost()) {
            //验证权限
            if(!$this->popedom["modify"] || !Session::get('edittplpass')){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                    return $result;                    
                }
            }
            $post = input('post.', '', null);
            $content = input('post.content', '', null);
            $filename = !empty($post['filename']) ? trim($post['filename']) : '';
            $content = !empty($content) ? $content : '';
            $activepath = !empty($post['activepath']) ? trim($post['activepath']) : '';
            if (empty($filename) || empty($activepath)) {
                $result['status'] = false;
                $result['msg']  = '参数有误';
                return $result;
            }
            $r = $this->filemanagerLogic->editFile($filename, $activepath, $content);
            if ($r === true) {
                $result['status'] = true;
                $result['msg']    = '操作成功！';
                $result['url'] = url('/channel.Filemanager/lists', array('activepath'=>$this->filemanagerLogic->replace_path($activepath, ':', false)))->suffix(false)->domain(true)->build();
                return $result;
            } else {
                $result['status'] = false;
                $result['msg']  = '操作失败！';
                return $result;
            }
        }
        $activepath = input('param.activepath/s', '', null);
        $activepath = $this->filemanagerLogic->replace_path($activepath, ':', true);
        $filename = input('param.filename/s', '', null);
        $activepath = str_replace("..", "", $activepath);
        $filename = str_replace("..", "", $filename);
        $path_parts  = pathinfo($filename);
        $path_parts['extension'] = strtolower($path_parts['extension']);
        // 不允许越过指定最大级目录的文件编辑
        $tmp_max_dir = preg_replace("#\/#i", "\/", $this->filemanagerLogic->maxDir);
        if (!preg_match("#^".$tmp_max_dir."#i", $activepath)) {
            $this->errorNotice('您没有操作权限！');
        }
        // 允许编辑的文件类型
        if (!in_array($path_parts['extension'], $this->filemanagerLogic->editExt)) {
            $this->errorNotice('只允许操作文件类型如下：'.implode('|', $this->filemanagerLogic->editExt));
        }
        // 读取文件内容
        $file = $this->baseDir."$activepath/$filename";
        $file = str_replace("\/", "/", $file);
        $content = "";
        if(is_file($file)){
            $filesize = filesize($file);
            if (0 < $filesize) {
                $fp = fopen($file, "r");
                $content = fread($fp, $filesize);
                if (mb_detect_encoding($content, 'UTF-8', true) === false) {
                    $content = iconv('GB2312', 'UTF-8', $content);
                }
                fclose($fp);
                if ('css' != $path_parts['extension']) {
                    $content = htmlspecialchars($content, ENT_QUOTES);
                    $content = preg_replace("/(@)?eval(\s*)\(/i", 'intval(', $content);
                }
            }
        }
        if($path_parts['extension'] == 'js'){
            $extension = 'text/javascript';
        } else if($path_parts['extension'] == 'css'){
            $extension = 'text/css';
        } else {
            $extension = 'text/html';
        }
        $info = array(
            'filename'  => $filename,
            'activepath'=> $activepath,
            'extension' => $extension,
            'content'   => $content,
        );
        $this->assign('info', $info);
        return $this->fetch();
    }
    //新建文件
    public function newfile()
    {
        $result = ['status' => false,'msg' => '失败','url' => ''];
        if (Request::isPost()) {
            //验证权限
            if(!$this->popedom["add"] || !Session::get('edittplpass')){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.add')];
                    return $result;                    
                }
            }
            $post = input('post.', '', null);
            $content = input('post.content', '', null);
            $filename = !empty($post['filename']) ? trim($post['filename']) : '';
            $content = !empty($content) ? $content : '';
            $activepath = !empty($post['activepath']) ? trim($post['activepath']) : '';
            if (empty($filename) || empty($activepath)) {
                $result['status'] = false;
                $result['msg']  = '参数有误';
                return $result;
            }
            $r = $this->filemanagerLogic->editFile($filename, $activepath, $content);
            if ($r === true) {
                $result['status'] = true;
                $result['msg']    = '操作成功！';
                $result['url'] = url('/channel.Filemanager/lists', array('activepath'=>$this->filemanagerLogic->replace_path($activepath, ':', false)))->suffix(false)->domain(true)->build();
                return $result;
            } else {
                $result['status'] = false;
                $result['msg']  = '参数有误';
                return $result;
            }
        }
        $activepath = input('param.activepath/s', '', null);
        $activepath = $this->filemanagerLogic->replace_path($activepath, ':', true);
        $filename = 'newfile.html';
        $content = "";
        $info = array(
            'filename'  => $filename,
            'activepath'=> $activepath,
            'content'   => $content,
            'extension' => 'text/html',
        );
        $this->assign('info', $info);
        return $this->fetch();
    }

    //设置模板风格
    public function ajax_set_theme()
    {
        $theme = input('post.theme/s');
        if (Request::isPost() && !empty($theme)) {
            //验证权限
            if(!$this->popedom["modify"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                    return $result;                    
                }
            }
            tpCache('system', ['system_tpl_theme'=>$theme]);
            Cache::clear('configsystem'); //清空缓存
            /*
            $dir = ROOT_PATH.'extend/model/template';
            if (is_dir($dir)){
                if ($oldname1 = opendir($dir)){
                    while (($file = readdir($oldname1)) !== false){
                        $oldname = $file;
                    }
                    closedir($oldname1);
                }
            }
            if($oldname != $theme){
                rename(iconv('UTF-8','UTF-8',$oldname), iconv('UTF-8','UTF-8',$theme));
            }*/
            $result = ['status' => true, 'msg' => '切换成功'];
            return $result;
        }
        $result = ['status' => false, 'msg' => '切换失败'];
        return $result;
    }


}
